package com.tdam2011.grupo05.control.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

import com.tdam2011.grupo05.processor.Processor;
import com.tdam2011.grupo05.services.constant.ServiceActions;
import com.tdam2011.grupo05.utils.parser.XMLParser;
import com.tdam2011.grupo05.utils.parser.XMLParser.Entry;

public class HttpWorker implements Runnable {

	private final static String TAG = "HttpWorker";
	private final Processor mProcessor;
	private final String mUrl;
	private final XMLParser mParser;

	public HttpWorker(Processor processor, String url) {
		mProcessor = processor;
		mUrl = url;
		mParser = new XMLParser();
	}

	public Processor getProcessor() {
		return mProcessor;
	}

	@Override
	public void run() {
		StringEntity request = null;
		Entry entry = null;
		String result = ServiceActions.SENDED_FAIL;

		try {
			request = mProcessor.handleRequest();
			entry = execute(request);
			result = ServiceActions.SENDED_OK;
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "UnsupportedEncodingException", e);
		} catch (ClientProtocolException e) {
			Log.e(TAG, "ClientProtocolException", e);
		} catch (IOException e) {
			Log.e(TAG, "IOException", e);
		} catch (XmlPullParserException e) {

		} catch (Exception e) {
			Log.e(TAG, "all exceptions", e);
		}
		mProcessor.handleResponse(entry, result);
	}

	public Entry execute(StringEntity request) throws IOException,
			XmlPullParserException {
		Entry entry = null;
		Log.d(TAG, "executing");
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(mUrl);
		httpPost.setEntity(request);

		HttpResponse httpResponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpResponse.getEntity();

		InputStream inputStream = httpEntity.getContent();

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String buffer = "";
		StringReader stringReader = null;

		while ((buffer = bufferedReader.readLine()) != null) {
			stringReader = new StringReader(buffer);
			Log.i(TAG, buffer);
		}
		if (stringReader != null) {
			entry = mParser.parse(stringReader);
		}
		return entry;
	}

}
